//
//  XRmenuHelper.m
//  XRmenu
//
//  Created by yangxh on 11-3-23.
//  Copyright 2011 E0571. All rights reserved.
//

#import "XRmenuHelper.h"
#import "NSString+Additions.h"
#import "XRmenuFileManage.h"

@interface XRmenuHelper()
+ (id)apiReturnResultHttpGetModeWithUrl:(NSString *)urlAddress Error:(NSError **)outError;
@end

@implementation XRmenuHelper

#pragma mark private
+ (id)apiReturnResultHttpGetModeWithUrl:(NSString *)urlAddress Error:(NSError **)outError
{
	NSDictionary *result = nil;
	
	NSString *response = [Http httpGet:urlAddress Error:outError];
	if (YES) {//!*outError
		response = [response stringByReplacingOccurrencesOfRegex:@"([{,]{1})(\\w+)(:)" withString:@"$1\"$2\"$3"];
		response = [response stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
		result = [response JSONValue];
		if (result) {
			//return result;
		}else {
			NSString *errorMsg = [[NSString alloc] initWithFormat:@"%@",@"不好意思，出错了！"];
			NSDictionary *uDict = [NSDictionary dictionaryWithObject:errorMsg forKey:NSLocalizedDescriptionKey];
			[errorMsg release];
			if (outError) {
				*outError = [NSError errorWithDomain:@"XRmenu" code:-1000 userInfo:uDict];
			}
		}
	}
	
	return result;
}
#pragma mark XRmenu
+ (id)getDataFromInternet:(NSString *)urlAddress Error:(NSError **)outError{
    return [self apiReturnResultHttpGetModeWithUrl:urlAddress Error:outError];
}

#pragma mark test
+ (void)testHttpsConection
{
	NSError *error = nil;//
	NSString *temp = [Http httpGet:@"http://192.168.8.58/wmenu/pluplutag/update/11" Error:&error];
    DebugLog(@"%@",temp);
	
	if (error) {
		DebugLog(@"%@", [error localizedDescription]);
	}else {
		DebugLog(@"%@", temp);
	}

}

#pragma mark 连接 
//取授权服务器地址
+ (NSString *)centerUrlWithError:(XRmenuError **)outError
{
	//*outError = [XRmenuError errorWithDomain:@"df" code:1 userInfo:nil];
    
    return @"http://update.com.cn";
	
	//NSArray *urls = nil;
	//NSString *resultUrl = nil;
	//1. 从网络 或 本地plist中取出授权服务器队列
	//NSString *centerUrlPath = [[XRmenuFileManage documentPath] stringByAppendingPathComponent:@"CenterUrl"];
	//if ([XRmenuFileManage fileExistByPath:centerUrlPath]) {
//		
//		urls = [NSArray arrayWithContentsOfFile:centerUrlPath];
//		
//	}else {
//		NSString *baseUrl = @""; //从固定链接中取
//		urls = [self apiReturnResultHttpGetModeWithUrl:baseUrl Error:outError];
//		if (*outError) {
//			DebugLog(@"取授权服务器地址错误 ：%@", [*outError localizedDescription]);
//		}else {
//			[urls writeToFile:centerUrlPath atomically:YES];
//		}
//
//	}
	
	//2. 遍历 授权服务器队列 取出第一个 工作正常的服务器
	
}

//是否授权
+ (NSString *)getLinsence:(NSString *)serverUrl UUID:(NSString *)uuid Error:(XRmenuError **)outError
{
	//BOOL status = NO;
	
	NSString *url = [NSString stringWithFormat:@"%@/%@/%@",serverUrl,@"License",uuid];
	NSString *response = [Http httpGet:url Error:outError];
	
	//if ([[response lowercaseString] isEqualToString:@"true"]) {
//		DebugLog(@"%@", @"Login success");
//		status = YES;
//	}else {
//		DebugLog(@"%@", @"Login failure.");
//	}
//
//	return status;
	return response;
}

//向center登记硬件信息
+ (BOOL)reportDeviceInfomationToCenter:(NSString *)centerUrl Name:(NSString *)aName Type:(NSInteger)aType 
								 Model:(NSString *)aModel OSVersion:(NSString *)aOSVersion SN:(NSString *)aSN 
								  UDID:(NSString *)aUDID BundleVersion:(NSString *)aBundleVersion TokenKey:(NSString *)aTokenKey
								 Error:(XRmenuError **)outError
{
	BOOL status = NO;
	NSString *needBase64 = [NSString stringWithFormat:@"%@|%d|%@|%@|%@|%@|%@|%@",
							trim(aName),aType,trim(aModel),aOSVersion,aSN,aUDID,aBundleVersion,aTokenKey];
	
	NSString *alerdayBase64 = [needBase64 base64StringEncode];
	DebugLog(@"Base64: %@", alerdayBase64);
	DebugLog(@"Base64Decode: %@", [alerdayBase64 base64StringDecode]);
	
	//NSString *url = [NSString stringWithFormat:@"%@/Device/%@",centerUrl,alerdayBase64];
	NSString *url = [NSString stringWithFormat:@"%@/Device/%@/%d/%@/%@/%@/%@/%@/%@",
					 centerUrl,aName,aType,aModel,aOSVersion,aSN,aUDID,aBundleVersion,aTokenKey];
	NSString *response = [Http httpGet:url Error:outError];
	
	if (!*outError) {
		DebugLog(@"Device infomation report result: %@", response);
		status = YES;
	}else {
		DebugLog(@"%@", [*outError localizedDescription]);
	}
	return status;
}

//取餐厅信息
+ (IRestaurant *)restaurantInfoFromCenter:(NSString *)centerUrl UUID:(NSString *)aUUID Error:(XRmenuError **)outError
{
	NSString *url = [NSString stringWithFormat:@"%@/%@/%@", centerUrl,@"Device",aUUID];
	NSDictionary *info = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		return [IRestaurant iRestaurantByParse:info];
	}else {
		DebugLog(@"%@", [*outError localizedDescription]);
	}
	
	return nil;
}

//取当前餐厅数据更新地址
+ (NSString *)getUpdateUrl:(NSString *)centerUrl UUID:(NSString *)aUUID Error:(XRmenuError **)outError
{
	NSString *url = [NSString stringWithFormat:@"%@/UpdateUrl/%@", centerUrl, aUUID];
	NSString *response = [Http httpGet:url Error:outError];
	if (!*outError) {
		DebugLog(@"getUpdateUrl 成功!");
		return response;
	}else {
		DebugLog(@"getUpdateUrl 失败： %@", [*outError localizedDescription]);
	}
	
	return nil;
}

#pragma mark -
#pragma  mark XRmenu菜谱下载




#pragma mark -
#pragma mark CMS Data
//根据udid取部门编号
+ (IDepartment *)departmentIdWithBaseUrl:(NSString *)baseUrl UUID:(NSString *)uuid Error:(XRmenuError **)outError
{
    NSString *url = [NSString stringWithFormat:@"%@/Department/udid=%@",BaseURL(baseUrl), uuid];
    NSDictionary *result = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
    if (!*outError) {
        IDepartment *dept = [IDepartment iDepartmentByParse:result];
        return dept;
    }else{
        DebugLog(@"取部门编号错误:%@", [*outError localizedDescription]);
    }
    return nil;
}

//向CMS报告信息
+ (BOOL)reportToCMS:(NSString *)baseUrl Model:(NSString *)aModel SN:(NSString *)aSN Vsersion:(NSString *)aVersion
					 UDID:(NSString *)aUDID Type:(NSInteger)aType Name:(NSString *)aName Mac:(NSString *)aMac
					   IP:(NSString *)aIpAddress
{
	BOOL status = NO;
	NSString *url = [NSString stringWithFormat:@"%@/XRmenuIpad/m=%@/sn=%@/v=%@/uid=%@/t=%d/n=%@/mac=%@/ip=%@",
					 BaseURL(baseUrl),aModel,aSN,aVersion,aUDID,aType,aName,aMac,aIpAddress];
	NSError *error = nil;
	NSString *response = [Http httpGet:url Error:&error];
	
	if (!error) {
		DebugLog(@"Device infomation report result: %@", response);
		if ([response isEqualToString:@"true"]) {
			status = YES;
		}else {
			status = NO;
		}
	}else {
		DebugLog(@"%@", [error localizedDescription]);
	}
	return status;
}

+ (BOOL)reportToCMS:(NSString *)baseUrl UDID:(NSString *)aUDID{
    BOOL status = NO;
	NSString *url = [NSString stringWithFormat:@"%@/update/XRmenuIpad/%@",BaseURL(baseUrl),aUDID];
	NSError *error = nil;
	NSString *response = [Http httpGet:url Error:&error];
	
	if (!error) {
		DebugLog(@"Device infomation report result: %@", response);
		if ([response isEqualToString:@"true"]) {
			status = YES;
		}else {
			status = NO;
		}
	}else {
		DebugLog(@"%@", [error localizedDescription]);
	}
	return status;
}

+ (NSString *)sendMyOrders:(NSString *)sendOrderJson Error:(XRmenuError **)outError{
    //组装Dictionary
    NSDictionary *dicJson=[NSDictionary dictionaryWithObjectsAndKeys:sendOrderJson,@"myorderjson", nil];
    //获取url
    NSString *baseUrl = [[NSUserDefaults standardUserDefaults] stringForKey:@"download_url"];
	NSString *url = [NSString stringWithFormat:@"%@/update/SendMyOrder",BaseURL(baseUrl)];
    return [Http httpPost:url Post:dicJson Error:outError];
}

//取欢迎页信息
+ (IWelcomePage *)welcomePage:(NSString *)baseUrl UUID:(NSString *)uuid Error:(XRmenuError **)outError
{
	NSString *url = [NSString stringWithFormat:@"%@/Welcome/%@", BaseURL(baseUrl), uuid];
	
	NSDictionary *result = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		return [IWelcomePage iWelcomePageByParse:result];
	}
	else {
		DebugLog(@"%@", [*outError localizedDescription]);
	}
	return nil;
}

// 取所有菜本
+ (NSArray *)menuBooksAll:(NSString *)baseUrl DepartmentId:(NSString *)departmentId Error:(XRmenuError **)outError
{
	
	NSArray *result = nil;
    NSString *url = [NSString stringWithFormat:@"%@/Menu/d=%@",BaseURL(baseUrl),departmentId];
    
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IMenu *menu = [IMenu iMenuByParse:item];
            [returnArr addObject:menu];
		}
		result = returnArr;
	}
	
	return result;
}

// 根据Menu编号 取  Catalogs
+ (NSArray *)catalogsAll:(NSString *)baseUrl menuId:(NSString *)aMenuId Error:(XRmenuError **)outError
{
	
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Catalogs/m=%@", BaseURL(baseUrl),aMenuId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			ICatalogs *catalogs = [ICatalogs iCatalogsByParse:item];
			[returnArr addObject:catalogs];
			
		}
		result = returnArr;
	}
	
	return result;
}

// 根据 Catalogs 编号 取子 Catalogs
+ (NSArray *)catalogsGetSubCatelogs:(NSString *)baseUrl parentCatalogsId:(NSString *)catalogId Error:(XRmenuError **)outError
{
    NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Catalogs/p=%@", BaseURL(baseUrl),catalogId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			ICatalogs *catalogs = [ICatalogs iCatalogsByParse:item];
            [returnArr addObject:catalogs];
			
		}
		result = returnArr;
	}
	
	return result;
}

// 根据 Catalogs 编号 取 Product
+ (NSArray *)productAll:(NSString *)baseUrl catalogsId:(NSString *)aCatalogsId Error:(XRmenuError **)outError
{	
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Product/c=%@", BaseURL(baseUrl), aCatalogsId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IProduct *product = [IProduct iProductByParse:item];
			[returnArr addObject:product];
		}
		result = returnArr;
	}
	
	return result;
}

// 取所有的Dish
+ (NSArray *)dishesAll:(NSString *)baseUrl DepartmentId:(NSString *)departmentId Error:(XRmenuError **)outError
{	
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Dishes/d=%@", BaseURL(baseUrl),departmentId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IDish *dish = [IDish iDishByParse:item];
			[returnArr addObject:dish];
		}
		result = returnArr;
	}
	
	return result;
}

// 取所有的 Cigarette
+ (NSArray *)cigarettesAll:(NSString *)baseUrl DepartmentId:(NSString *)departmentId Error:(XRmenuError **)outError
{
    NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Cigarettes/d=%@",BaseURL(baseUrl),departmentId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			ICigarette *cigarette = [ICigarette iCigaretteByParse:item];
			[returnArr addObject:cigarette];
		}
		result = returnArr;
	}
	
	return result;
}

// 取所有的 Drink
+ (NSArray *)drinksAll:(NSString *)baseUrl DepartmentId:(NSString *)departmentId Error:(XRmenuError **)outError
{
    NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Drinks/d=%@",BaseURL(baseUrl),departmentId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IDrink *drink = [IDrink iDrinkByParse:item];
			[returnArr addObject:drink];
		}
		result = returnArr;
	}
	
	return result;
}

//9.  取所有的 SeasonDish
+ (NSArray *)seasonDishesAll:(NSString *)baseUrl DepartmentId:(NSString *)departmentId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
    NSString *url = [NSString stringWithFormat:@"%@/SeasonDishes/d=%@",BaseURL(baseUrl),departmentId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			ISeasonDish *seasonDish = [ISeasonDish iSeasonDishByParse:item];
			[returnArr addObject:seasonDish];
		}
		result = returnArr;
	}
	
	return result;
}

//10.  取所有的 SetMail
+ (NSArray *)setMealsAll:(NSString *)baseUrl DepartmentId:(NSString *)departmentId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/SetMeals/d=%@",BaseURL(baseUrl), departmentId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			ISetMeal *setMeal = [ISetMeal iSetMealByParse:item];
			[returnArr addObject:setMeal];
		}
		result = returnArr;
	}
	
	return result;
}

//11. 根据 SetMail 编号 取 所有的 Product 编号
+ (NSArray *)products:(NSString *)baseUrl bySetMealId:(NSString *)setMealId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Products/sm=%@", BaseURL(baseUrl), setMealId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IProduct *product = [IProduct iProductByParse:item];
			[returnArr addObject:product];
		}
		result = returnArr;
	}
	
	return result;
}

//12. 根据 Product 编号 取 所有的  SetMail 编号
+ (NSArray *)setMeals:(NSString *)baseUrl byProductId:(NSString *)productId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/SetMeals/p=%@", BaseURL(baseUrl), productId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			ISetMeal *setMeal = [ISetMeal iSetMealByParse:item];
			[returnArr addObject:setMeal];
		}
		result = returnArr;
	}
	
	return result;
}

//13. 取所有的 标签
+ (NSArray *)productTagsAll:(NSString *)baseUrl DepartmentId:(NSString *)departmentId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Tags/d=%@",BaseURL(baseUrl),departmentId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IProductTag *pTag = [IProductTag iProductTagByParse:item];
			[returnArr addObject:pTag];
		}
		result = returnArr;
	}
	
	return result;
}

//14. 取所有的 改码
+ (NSArray *)specCodesAll:(NSString *)baseUrl DepartmentId:(NSString *)departmentId Error:(XRmenuError **)outError
{
    NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/SpecCodes",BaseURL(baseUrl)];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			ISpecCode *specCode = [ISpecCode iSpecCodeByParse:item];
			[returnArr addObject:specCode];
		}
		result = returnArr;
	}
	
	return result;
}

//15. 根据Product  编号取 标签
+ (NSArray *)productTags:(NSString *)baseUrl byProductId:(NSString *)productId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Tags/p=%@",BaseURL(baseUrl),productId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IProductTag *pTag = [IProductTag iProductTagByParse:item];
			[returnArr addObject:pTag];
		}
		result = returnArr;
	}
	
	return result;
}

//16. 根据标签编号 取 Product
+ (NSArray *)products:(NSString *)baseUrl byProductTagId:(NSString *)productTagId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Products/t=%@",BaseURL(baseUrl),productTagId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IProduct *product = [IProduct iProductByParse:item];
			[returnArr addObject:product];
		}
		result = returnArr;
	}
	
	return result;
}

//17. 根据 改码编号 取 Product ---
+ (NSArray *)products:(NSString *)baseUrl bySpecCodeId:(NSString *)specCodeId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/Products/s=%@",BaseURL(baseUrl),specCodeId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IProduct *product = [IProduct iProductByParse:item];
			[returnArr addObject:product];
		}
		result = returnArr;
	}
	
	return result;
}

//18. 根据 Product 编号 取 改码
+ (NSArray *)specCodes:(NSString *)baseUrl byProductId:(NSString *)productId Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/SpecCodes/p=%@",BaseURL(baseUrl),productId];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			ISpecCode *specCode = [ISpecCode iSpecCodeByParse:item];
			[returnArr addObject:specCode];
		}
		result = returnArr;
	}
	
	return result;
}

// 取 图片/视频等 文件
+ (NSArray *)docFilesAll:(NSString *)baseUrl Error:(XRmenuError **)outError
{
	NSArray *result = nil;
	NSString *url = [NSString stringWithFormat:@"%@/dishphoto/",BaseURL(baseUrl)];
	NSArray *arr = [self apiReturnResultHttpGetModeWithUrl:url Error:outError];
	if (!*outError) {
		NSMutableArray *returnArr = [NSMutableArray arrayWithCapacity:[arr count]];
		NSDictionary *item = nil;
		for (item in arr) {
			IDocFile *doc = [IDocFile iDocFileByParse:item];
			[returnArr addObject:doc];
		}
		result = returnArr;
	}
	
	return result;
}

+ (BOOL)downloadFile:(NSString *)url LocalFolder:(NSString *)localFolder
{
	[Http httpDownload:url LocalFolder:localFolder];
	return YES;
}

+(DishLanguageEx*)getCurrentEx:(Product*)aProduct
{
	for (DishLanguageEx* item in aProduct.rsToDish.rsToLanguage){
		 if ([item.dLanguage isEqualToString:APPSESSION.language]) {
			 return item;
		 }
	}
	
	return nil;
	
	
}
@end
